#!/usr/bin/env python
'''
 process a *.h.in file to produce a *.h file
'''

import sys
import re

config = {
    'PROJECT_VERSION_MAJOR' : 2,
    'PROJECT_VERSION_MINOR' : 0,
    'PROJECT_VERSION_PATCH' : 1,
    'PROJECT_VERSION' : '2.0.1',
    'CONFIG_MACHINE_ENDIANNESS' : 1, # little endian
}

defines = {}

h_in = sys.argv[1]
h = sys.argv[2]
print("Processing %s to %s" % (h_in, h))

txt = open(h_in, 'r').read()

for c in sorted(config.keys(), key=len, reverse=True):
    txt = txt.replace("@%s@" % c, str(config[c]))

for c in sorted(defines.keys(), key=len, reverse=True):
    if defines[c] != 0:
        txt = txt.replace("#cmakedefine %s" % c, "#define %s %u" % (c, defines[c]))
    else:
        txt = txt.replace("#cmakedefine %s" % c, "// #define %s %u" % (c, defines[c]))

matches = re.findall(r'@(\w+)@', txt)
if len(matches) > 0:
    print("Missing config elements: ", matches)
    sys.exit(1)

matches = re.findall(r'#cmakedefine\s+\w+', txt)
if len(matches) > 0:
    print("Missing #cmakedefine elements: ", matches)
    sys.exit(1)

open(h, 'w').write(txt)